package com.wangdao.wechatmall.realm;

import com.wangdao.wechatmall.bean.pojo.Admin;
import com.wangdao.wechatmall.mapper.AdminMapper;
import com.wangdao.wechatmall.mapper.PermissionMapper;
import org.apache.shiro.authc.*;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.crypto.hash.SimpleHash;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.util.ByteSource;
import org.bouncycastle.pqc.math.linearalgebra.ByteUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;

/**
 * shiro相关的配置
 *
 * @author ZhangXiao on 2021/7/9
 */
@Component
public class AdminRealm extends AuthorizingRealm {

    @Autowired
    AdminMapper adminMapper;


    @Autowired
    PermissionMapper permissionMapper;

    //处理认证信息
    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken authenticationToken) throws AuthenticationException {

        UsernamePasswordToken token = (UsernamePasswordToken) authenticationToken;
        String username = token.getUsername();
        List<String> strings = adminMapper.selectPasswordByName(username);
        String credential = strings.size() >= 1 ? strings.get(0) : null;
        SimpleAuthenticationInfo simpleAuthenticationInfo = new SimpleAuthenticationInfo(
                username, credential, ByteSource.Util.bytes(username), this.getName());

        /**
         * 加密后的密文查看
         * "MD5" → 加密算法
         * token.getPassword() → 登录时输入的密码
         * username → 加盐
         * 3 → 迭代次数
         */

        SimpleHash md5 = new SimpleHash("MD5", token.getPassword(), username, 3);
        System.out.println(md5);
        return simpleAuthenticationInfo;
    }

    //处理授权信息
    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principalCollection) {
        String username = (String) principalCollection.getPrimaryPrincipal();
        Admin admin = adminMapper.queryAdminByName(username);

        List<String> permissions = new ArrayList<>();
        Integer[] roleIds = admin.getRoleIds();
        //通过roleIds去查出permission信息
        for (int i = 0; i < roleIds.length; i++) {
            List<String> strings = new ArrayList<>();
            strings = permissionMapper.selectPermissionByRoleId(roleIds[i]);
            permissions.addAll(strings);
        }
        SimpleAuthorizationInfo authorizationInfo = new SimpleAuthorizationInfo();
        authorizationInfo.addStringPermissions(permissions);
        return authorizationInfo;
    }


}
